<template>
	<view class="my-message">
		<!-- tab -->
		<view class="tab">
			<view class="tab-item active">{{i18n.messageBox}}</view>
			<view class="tab-item" @tap="toMessagePlatform">{{i18n.platformAnnouncement}}</view>
			<view :class="['tab-item',messageCount?'unread-tip':'']" @tap="toMessageNotice">{{i18n.systemNotification}}
			</view>
		</view>

		<!-- 客服消息 -->
		<view class="service-message" v-if="conversations.length">
			<view class="item unread" v-for="(item, index) in conversations" :key="index"
				@tap="gotochat(item.shopId,item.chatType)">
				<view class="logo">
					<image :src="item.pic?item.pic:'/static/images/icon/customer-service.png'" />
				</view>
				<view class="text-box">
					<view class="name">{{item.friendName}}</view>
					<view class="des">{{item.latestMsg}}</view>
				</view>
				<view class="time-box">
					<view class="time">{{item.timeStr}}</view>
					<view class="unread-box" v-if="item.unread">
						<view class="number">{{item.unread}}</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 为空 -->
		<view class="empty" v-if="!conversations.length">
			<view class="img">
				<image :src="pictureDomain+'not-found.png'"></image>
			</view>
			<view class="text">{{i18n.youHaveNoMessages}}</view>
		</view>

	</view>
</template>

<script>
	var util = require("@/utils/util");
	import http from "@/utils/http.js";
	import config from "@/utils/config.js";
	export default {
		data() {
			return {
				pictureDomain: config.pictureDomain,
				userlist: [],
				imSocketTask: null,
				conversations: [],
				messageCount: null
			}
		},

		computed: {
			i18n() {
				return this.$t('index')
			}
		},

		onload() {
			// this.openWs()
			// this.getMyNotifyRemind()
		},

		onShow() {
			//头部导航标题
			uni.setNavigationBarTitle({
				title: this.i18n.messageBox
			});

			this.getConversations()
			this.openWs()
		},
		onHide() {
			this.closeWs()
		},

		methods: {

			openWs() {
				this.imSocketTask = uni.connectSocket({
					url: config.imWsDomain + '/im/websocket/user/' + uni.getStorageSync('token').substring(
					6), //仅为示例，并非真实接口地址。
					complete: () => {}
				});

				this.imSocketTask.onMessage((res) => {
					let result = JSON.parse(res.data)
					console.log('onMessage:' + res.data)
					// 
					if (result.code == 10) {
						console.log("无法获取用户信息，跳转到登陆页面")
						return
					}
					if (result.code == 11) {
						console.log("账户已在别处登录，请刷新")
						return
					}
					if (result.code == 12) {
						console.log("对方不在线")
						return
					}
					if (!result.obj) {
						return
					}
					let msgItem = result.obj
					// 消息内容
					let msgContent = ''
					// 图片消息
					if (msgItem.type === 1) {
						msgContent = '[图片]'
					} else {
						msgContent = msgItem.content
					}
					for (var i = 0; i < this.conversations.length; i++) {
						var item = this.conversations[i]
						// 更新最新消息
						if (msgItem.shopId === item.shopId) {
							item.latestMsg = msgContent
							item.timeStr = msgItem.timeStr
							this.conversations.splice(i, 1)
							break
						}
					}

					this.conversations.unshift({
						pic: msgItem.shopLogo,
						friendName: msgItem.shopName,
						shopId: msgItem.shopId,
						latestMsg: msgContent,
						timeStr: msgItem.timeStr
					})
					this.setData({
						conversations: this.conversations
					})

				})
			},

			//判断是否为JSON格式
			isJSON(str) {
				if (typeof str == 'string') {
					try {
						JSON.parse(str);
						return true;
					} catch (e) {
						return false;
					}
				}
			},

			getConversations() {
				var params = {
					domain: config.imDomain,
					url: "/p/user/conversations",
					method: "POST",
					callBack: res => {
						if (res && res.records.length) {
							this.conversations = res.records.filter(item => {
								let a = this.isJSON(item.latestMsg)
								// 店铺状态 下线由0改为2  1营业
								if (item.shopStatus == 2) {
									return false
								} else if (item.type === 1) {
									item.latestMsg = '[图片]'
									return true
								} else if (a && JSON.parse(item.latestMsg) instanceof Object) {
									item.latestMsg = '[' + this.i18n.productLinks + ']' //商品链接
									return true
								} else {
									return true
								}
							});
						}
					}
				};
				http.request(params);
			},
			closeWs() {
				this.imSocketTask.close()
				this.imSocketTask = null
			},
			gotochat(shopId, chatType) {
				chatType === 1 ? shopId = 0 : shopId = shopId
				uni.navigateTo({
					url: 'chatIm?shopid=' + shopId
				})
			},

			/**
			 * 获取未读消息数量
			 */
			getMyNotifyRemind() {
				var params = {
					url: '/p/myNotifyLog/unReadCount',
					method: 'GET',
					dontTrunLogin: true,
					data: {},
					callBack: res => {
						if (uni.getStorageSync('token')) {
							this.setData({
								messageCount: res
							});
						}
					}
				};
				http.request(params)
			},

			// 去平台公告
			toMessagePlatform() {
				uni.navigateTo({
					url: '/packageUser/pages/recent-news/recent-news'
				})
			},

			// 去系统通知
			toMessageNotice() {
				util.checkAuthInfo(() => {
					uni.navigateTo({
						url: '/packageUser/pages/recent-news/recent-news?showMessage=1'
					})
				})
			},

		}
	}
</script>

<style>
	@import "./my-message.css";
</style>
